//
//  AirportsDetailsViewController.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/9.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import UIKit
import MapKit
import RxSwift
import RxCocoa

class AirportsDetailsViewController: UIViewController, Storyboardable {

    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var airportName: UILabel!
    @IBOutlet weak var distanceLabel: UILabel!
    @IBOutlet weak var countryLabel: UILabel!
    @IBOutlet weak var runawayLengthLabel: UILabel!
    
    private let bag: DisposeBag = DisposeBag()
    
    private var viewModel: AirportDetailViewPresentable!
    var viewModelBuilder: AirportDetailViewPresentable.ViewModelBuilder!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.viewModel = viewModelBuilder(())
        self.setupBinding()
        self.mapView.delegate = self
    }
}

extension AirportsDetailsViewController {

    func setupUI(_ viewModel: AirportViewPresentable) {
        self.airportName.text = viewModel.name
        self.distanceLabel.text = viewModel.formattedDistance
        self.countryLabel.text = viewModel.address
        self.runawayLengthLabel.text = viewModel.runawayLength
    }
    
    func setupMapUI(_ mapViewModel: AirportMapViewPresentable) {
        let airportPoint = CLLocationCoordinate2D(latitude: mapViewModel.airportLocation.lat, longitude: mapViewModel.airportLocation.lon)
        let currenPoint = CLLocationCoordinate2D(latitude: mapViewModel.currentLocation.lat, longitude: mapViewModel.currentLocation.lon)
        
        let airportPin = AirportPin(name: mapViewModel.airport.name, city: mapViewModel.airport.city, coordinate: airportPoint)
        let currentPin = AirportPin(name: "Current", coordinate: currenPoint)
        
        self.mapView.addAnnotations([currentPin, airportPin])
        
        // location 位置点的描述
        let currentPlacemark = MKPlacemark(coordinate: currenPoint)
        let airportPlacemark = MKPlacemark(coordinate: airportPoint)
        
        // 方向信息
        let directionRequest = MKDirections.Request()
        directionRequest.source = MKMapItem(placemark: currentPlacemark)
        directionRequest.destination = MKMapItem(placemark: airportPlacemark)
        // .automobile 驾驶，.walking 行人 .transit 公共
        directionRequest.transportType = .automobile
        
        let direction = MKDirections(request: directionRequest)
        // 根据提供的信息 开始异步计算 线路信息
        direction.calculate { [mapView] (response, error) in
            if let error = error {
                print("calculate error \(error.localizedDescription)")
                return
            }
            // 起点和终点之间的一条路线
            guard let route = response?.routes.first else { return }
            
            mapView?.addOverlay(route.polyline, level: .aboveRoads)
            
            UIView.animate(withDuration: 1.5) { [mapView, route] in
                let mapRect = route.polyline.boundingMapRect
                let region = MKCoordinateRegion(mapRect)
                // 设置地图区域为 线路的区域
                mapView?.setRegion(region, animated: true)
            }
        }
    }

    func setupBinding() {
        
        self.viewModel.output.airportDetail
            .map({ [weak self] in
                self?.setupUI($0)
            })
            .drive()
            .disposed(by: bag)
        
        self.viewModel.output.mapDetails
            .map({ [weak self] mapViewModel in
                self?.setupMapUI(mapViewModel)
            })
            .drive()
            .disposed(by: bag)
        
    }
}

extension AirportsDetailsViewController: MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let render = MKPolylineRenderer(overlay: overlay)
        render.strokeColor = .red
        render.lineWidth = 2.0
        return render
    }
    
}

//
//12.9716
//77.5946
